import fs from 'fs'
import { fileURLToPath,pathToFileURL } from 'url'


function findControllers(){
    let xDir=new URL('../controllers',import.meta.url)
    let controllerDir=fileURLToPath(xDir)

    if(fs.existsSync(controllerDir)){
        let allfile=fs.readdirSync(controllerDir)
        let allControllerfile=allfile.filter(item=>item.endsWith('.js')).map(item=>pathToFileURL(controllerDir+'/'+item))

        return allControllerfile
    }

    return null
}

function registerRouter(router,controllers){
    if(controllers ===null){
        return
    }

    controllers.forEach(async item=>{
        let {obj}=await import(item)

        for(var key in obj){
            let [keyMethod,keyPath] = key.split(' ')
            let keyFn = obj[key]

            if(keyMethod === 'get'){
                router.get(keyPath,keyFn)
            }
            if(keyMethod === 'post'){
                router.post(keyPath,keyFn)
            }
            if(keyMethod === 'put'){
                router.put(keyPath,keyFn)
            }
            if(keyMethod === 'delete'){
                router.delete(keyPath,keyFn)
            }
        }

        
    })
}


export const findAllControllers=findControllers
export const regRoute=registerRouter

